//
//  SHRBImageUploadController.m
//  JiFengDaRen
//
//  Created by SH_iOS on 2017/8/28.
//  Copyright © 2017年 SH_iOS. All rights reserved.
//

#import "SHRBImageModel.h"
#import "SHRBCollectionViewCell.h"
#import "SHRBImageUploadController.h"

@interface SHRBImageUploadController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property(nonatomic,strong)UICollectionView *rbImageUploadCollectionview;
@property(nonatomic,strong)NSMutableArray *rbDataSource;
@property(nonatomic,strong)NSDictionary *rbImgModel;
@property(nonatomic,assign)NSInteger selectedRow;
@property(nonatomic,assign)int successd;//1 已经上传过照片 0 为上传过照片


@end

@implementation SHRBImageUploadController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"信息补全";
    
    [self rbImageUploadCollectionview];
    [self getRongbangPaymentCheckImageView];
    


}

- (NSMutableArray *)rbDataSource{
    
    if (!_rbDataSource) {
        
        _rbDataSource = [NSMutableArray arrayWithCapacity:10];
    }
    
    
    return _rbDataSource;
}
- (void)getRongbangPaymentCheckImageView
{
    /*
     1010-手持身份证, 1011-身份证正面, 1012-身份证反面,1020-银行卡正面,
     1021-银行卡反面, 1022-手持银行卡正面,1023-信用卡正面
    */
    
    [MyDataService requestNoRSAAFURL:RONGBANG_PAYMENT_CHECK_IMAGE_VIEW httpMethod:@"GET" params:nil data:nil complection:^(id result) {
        self.successd = [result[@"success"] boolValue];
        self.rbImgModel = result[@"data"];
        
        for (int i = 0; i < self.rbImgModel.count; i ++) {
            
            
            switch (i) {
                case 0://1010 手持身份证
                {
                    SHRBImageModel *rbImgModel = [[SHRBImageModel alloc]init];
                    rbImgModel.imgKey = @"1010";
                    rbImgModel.imgTitle = @"手持身份证";
                    rbImgModel.isHaveImg = [self.rbImgModel[@"1010"][0] intValue];
                    rbImgModel.imgUrl = [NSString stringWithFormat:@"%@",self.rbImgModel[@"1010"][1]];
                    [self.rbDataSource addObject:rbImgModel];
                }
                    break;
                case 1://1011 身份证正面
                {
                    SHRBImageModel *rbImgModel = [[SHRBImageModel alloc]init];
                    rbImgModel.imgKey = @"1011";
                    rbImgModel.imgTitle = @"身份证正面";
                    rbImgModel.isHaveImg = [self.rbImgModel[@"1011"][0] intValue];
                    rbImgModel.imgUrl = [NSString stringWithFormat:@"%@",self.rbImgModel[@"1011"][1]];
                    [self.rbDataSource addObject:rbImgModel];

                }
                    break;
                case 2://1012 身份证反面
                {
                    SHRBImageModel *rbImgModel = [[SHRBImageModel alloc]init];
                    rbImgModel.imgKey = @"1012";
                    rbImgModel.imgTitle = @"身份证反面";
                    rbImgModel.isHaveImg = [self.rbImgModel[@"1012"][0] intValue];
                    rbImgModel.imgUrl = [NSString stringWithFormat:@"%@",self.rbImgModel[@"1012"][1]];
                    [self.rbDataSource addObject:rbImgModel];

                }
                    break;
                case 3://1020 银行卡正面
                {
                    SHRBImageModel *rbImgModel = [[SHRBImageModel alloc]init];
                    rbImgModel.imgKey = @"1020";
                    rbImgModel.imgTitle = @"银行卡正面";
                    rbImgModel.isHaveImg = [self.rbImgModel[@"1020"][0] intValue];
                    rbImgModel.imgUrl = [NSString stringWithFormat:@"%@",self.rbImgModel[@"1020"][1]];
                    [self.rbDataSource addObject:rbImgModel];

                }
                    break;
                case 4://1021 银行卡反面
                {
                    SHRBImageModel *rbImgModel = [[SHRBImageModel alloc]init];
                    rbImgModel.imgKey = @"1021";
                    rbImgModel.imgTitle = @"银行卡反面";
                    rbImgModel.isHaveImg = [self.rbImgModel[@"1021"][0] intValue];
                    rbImgModel.imgUrl = [NSString stringWithFormat:@"%@",self.rbImgModel[@"1021"][1]];
                    [self.rbDataSource addObject:rbImgModel];

                }
                    
                    break;
                case 5://1022 手持银行卡正面
                {
                    SHRBImageModel *rbImgModel = [[SHRBImageModel alloc]init];
                    rbImgModel.imgKey = @"1022";
                    rbImgModel.imgTitle = @"手持银行卡正面";
                    rbImgModel.isHaveImg = [self.rbImgModel[@"1022"][0] intValue];
                    rbImgModel.imgUrl = [NSString stringWithFormat:@"%@",self.rbImgModel[@"1022"][1]];
                    [self.rbDataSource addObject:rbImgModel];

                }
                    break;
                case 6://1023 信用卡正面
                {
                    SHRBImageModel *rbImgModel = [[SHRBImageModel alloc]init];
                    rbImgModel.imgKey = @"1023";
                    rbImgModel.imgTitle = @"信用卡正面";
                    rbImgModel.isHaveImg = [self.rbImgModel[@"1023"][0] intValue];
                    rbImgModel.imgUrl = [NSString stringWithFormat:@"%@",self.rbImgModel[@"1023"][1]];
                    [self.rbDataSource addObject:rbImgModel];

                }
                    
                    break;


                default:
                    break;
            }
            
            
        }
        
        [self.rbImageUploadCollectionview reloadData];

        SHLog(@"RONGBANG_PAYMENT_CHECK_IMAGE_VIEW%@",result);
        
    } failure:^(id erro) {
        
        SHLog(@"RONGBANG_PAYMENT_CHECK_IMAGE_VIEW%@",erro);

    }];



}

static NSString *const rbUICollectionViewCellReusableID = @"rbUICollectionViewCell";

- (UICollectionView *)rbImageUploadCollectionview{
    
    if (!_rbImageUploadCollectionview) {
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumLineSpacing = __I6Width(5);
        flowLayout.minimumInteritemSpacing = __I6Width(5);
        flowLayout.sectionInset = UIEdgeInsetsMake(__I6Width(20), __I6Width(10), __I6Width(10), __I6Width(10));
        flowLayout.itemSize = CGSizeMake(__I6Width(114),__I6Width(120) );
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;

        _rbImageUploadCollectionview = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0, KScreenWidth,KScreenHeight - KNAVIGATIONBARHEIGHT) collectionViewLayout:flowLayout];
        _rbImageUploadCollectionview.scrollEnabled = NO;
        _rbImageUploadCollectionview.backgroundColor = [UIColor whiteColor];
        _rbImageUploadCollectionview.showsHorizontalScrollIndicator = NO;
        _rbImageUploadCollectionview.showsVerticalScrollIndicator = NO;
        [_rbImageUploadCollectionview registerClass:[SHRBCollectionViewCell class] forCellWithReuseIdentifier:rbUICollectionViewCellReusableID];
        _rbImageUploadCollectionview.dataSource = self;
        _rbImageUploadCollectionview.delegate = self;
        [self.view addSubview:_rbImageUploadCollectionview];
    }
    return _rbImageUploadCollectionview;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.rbDataSource.count ;
}

//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
//{
//    //如果是头部视图 (因为这里的kind 有头部和尾部所以需要判断  默认是头部,严谨判断比较好)
//    /*
//     JHHeaderReusableView 头部的类
//     kHeaderID  重用标识
//     */
//    if (kind == UICollectionElementKindSectionHeader) {
////        SHHeaderReusableView *headerRV = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerReusableID forIndexPath:indexPath];
////        [headerRV setIconWithName:@"home_app" title:@"应用"];
//
//        return nil;
//
//    }else //有兴趣的也可以添加尾部视图
//    {
//        return nil;
//    }
//}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    SHRBCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:rbUICollectionViewCellReusableID forIndexPath:indexPath];
    cell.rbImageModel = self.rbDataSource[indexPath.row];
 
    
    return  cell;
    
}


#pragma mark - 点击打开相机 上传图片
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    //点击拍照
    
    [SHHelper checkUserAVAuthorizationStatusVc:self complection:^(AVAuthorizationStatus status) {
        self.selectedRow = indexPath.row;
        [self takePhoto];
        
    }];
    

    
    
}


//拍照
-(void)takePhoto{
    
    //****先检测相机权限
    
    
    //判断相机是否可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        //打开相机
        [self openImagePickerController:UIImagePickerControllerSourceTypeCamera];
        
        
        
        
    }else{
        
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"相机不可用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alert show];
    }
}
#pragma mark - 打开相机
- (void)openImagePickerController:(UIImagePickerControllerSourceType)type{
    
    UIImagePickerController  *picker = [[UIImagePickerController alloc]init];
    //指定资源类型
    picker.sourceType = type;
    //允许编辑
    picker.allowsEditing = YES;
    picker.delegate = self;
    //弹出
    [self presentViewController:picker animated:YES completion:nil];
    NSLog(@"开始拍照");
    
    
}
#pragma mark - 代理
#pragma mark 点击取消按钮 退出相机
#pragma mark 点击选择按钮

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage * image  = info[UIImagePickerControllerEditedImage];
    
    
    NSData *data;
    if (UIImagePNGRepresentation(image) == nil) {
        
        data = UIImageJPEGRepresentation([SHHelper thumbnailWithImageWithoutScale:image size:CGSizeMake(300, 300)], 1);
        
        
    } else {
        
        data = UIImagePNGRepresentation([SHHelper thumbnailWithImageWithoutScale:image size:CGSizeMake(300,300)]);
        
        
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self putImagToQinniuAndMySever:data];
    
    
}

#pragma mark - 七牛 Method
- (NSString *)tokenWithScope:(NSString *)scope{
    
    
    QiniuPutPolicy *policy = [QiniuPutPolicy new];
    policy.scope = scope;
    return [policy makeToken:QiniuAccessKey secretKey:QiniuSecretKey];
    
}

#pragma mark - 上传图片
- (void)putImagToQinniuAndMySever:(NSData *)data{
    
    NSString *date = [SHHelper getTodayDate];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [MyDataService requestAFURL:[NSString stringWithFormat:KGet_token,date] httpMethod:@"GET" params:nil data:nil complection:^(id result) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if (result[@"success"]) {
            
            NSString *token =  [self tokenWithScope:QiniuBucketName];
            
            //result[@"data"];
            QNUploadManager *upManager = [[QNUploadManager alloc] init];
            
            [upManager putData:data key:[NSString stringWithFormat:@"%@%d",date,arc4random()%100] token:token
                      complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                          
                          if (!resp ) {
                              return ;
                          }
                          
                          NSString *imageUrl = [KQN stringByAppendingString:resp[@"key"]];
                          
                          SHRBImageModel *rbImageModel    = self.rbDataSource[self.selectedRow];
                          rbImageModel.imgUrl = imageUrl;
                          [SHHomeModelView rongbangPaymentUploadImageFileType:rbImageModel.imgKey suffix:@"png" content:rbImageModel.imgUrl success:^(id result) {
                              
                              
                            
                              
                              [self.rbImageUploadCollectionview reloadData];
                          }];
                          
                          
                          
                     
                } option:nil];
        }
        
    } failure:^(id erro) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];

        
    }];
    
    
    
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
